package com.feizhaiyou.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.feizhaiyou.demo.enums.DataSourceType;
import com.feizhaiyou.demo.properties.DruidProperties;
import com.feizhaiyou.demo.ustils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.servlet.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * druid 配置多数据源
 *
 * @author Jason
 */
@Configuration
public class DruidConfig {

    private static final Logger log = LoggerFactory.getLogger(DruidConfig.class);

    // 设置数据源bean
    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    // 设置数据源bean
    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    // TODO 设置数据源bean 读取配置
    // 设置数据源beanName
    @Bean("slave2DataSource")
    // 读取的数据源配置
    @ConfigurationProperties("spring.datasource.druid.slave2")
    // 判断是否读取 enabled: true 读取
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave2", name = "enabled", havingValue = "true")
    public DataSource slave2DataSource(DruidProperties druidProperties) {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }


    /**
     * 设置指定的动态数据源 {@link DynamicDataSource}
     *
     * @param masterDataSource
     * @return
     */
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource masterDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        // 添加MUSTER动态数据源
        targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource);
        // 添加SLAVE动态数据源
        setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource");
        // TODO 设置数据源 参数：动态数据源集合，动态数据源key，对应数据源beanName
        setDataSource(targetDataSources, DataSourceType.SLAVE2.name(), "slave2DataSource");
        // 设置默认数据源和指定的动态数据源
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }

    /**
     * 设置数据源
     *
     * @param targetDataSources 动态数据源集合
     * @param sourceName        动态数据源key
     * @param beanName          bean名称
     */
    private void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) {
        try {
            // 通过名称从spring IOC中获取数据源bean
            DataSource dataSource = SpringUtils.getBean(beanName);
            // 添加到动态数据源集合
            targetDataSources.put(sourceName, dataSource);
        } catch (Exception e) {
            // enabled配置不为true的时候会报该错，即IOC中没有数据源bean
            // 不会加载到targetDataSources动态数据源集合中，如果注解有使用该数据源的key，则会使用默认的数据源
            log.warn("如果配置文件没有启用{}数据源，请忽略！",sourceName);
            log.error("IOC中没有{}，请检查数据源配置类beanName是否正确!",beanName);
        }
    }

    /**
     * 去除监控页面底部的广告
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter() {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
            }

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                chain.doFilter(request, response);
                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }

            @Override
            public void destroy() {
            }
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}
